//
//  JQFXHCalculationViewController.swift
//  jieqianfangxinhua
//
//  Created by 卢小艳 on 2025/8/22.
//

import Foundation
import UIKit
import SnapKit


class JQFXHCalculationViewController: HJYJBaseViewController {
    let monthsArr = [6, 9, 12]
    let typeArr = ["等额本息", "等额本金", "先息后本"]

    var selectedMonth = 0
    var buttonArr : [UIButton] = []
    
    
    var selectedType = 4
    var typebButtonArr : [UIButton] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.jqfxhBigViewBgccGray
        self.jqfxhIsNavBarjjHidden = true
        self.jqfxhCalculationUI()
        
    }
    
    
    
    lazy var jqfxhScrollggview : UIScrollView = {
        let jqfxhScrollggview = UIScrollView(frame: CGRectMake(0, 0, jqfxhScreenWidth, jqfxhScreenHeight))
        if #available(iOS 11.0, *) {
            jqfxhScrollggview.contentInsetAdjustmentBehavior = .never
        } else {
        }
        return jqfxhScrollggview
    }()
    
    lazy var jqfxhContentkkView : UIView = {
        let jqfxhContentkkView = UIView()
        jqfxhContentkkView.backgroundColor = UIColor.white
        jqfxhContentkkView.layer.cornerRadius = 12
        jqfxhContentkkView.layer.masksToBounds = true
        return jqfxhContentkkView
    }()
    
    lazy var jqfxhTopBgxxImg : UIImageView = {
        let jqfxhTopBgxxImg = UIImageView(image: UIImage(named: "jqfxh_home_top"))
        jqfxhTopBgxxImg.isUserInteractionEnabled = true
        return jqfxhTopBgxxImg
    }()
    
    lazy var jqfxhCalttPic : UIImageView = {
        let jqfxhCalttPic = UIImageView(image: UIImage(named: "jqfxh_cal_pic"))
        return jqfxhCalttPic
    }()
    
    lazy var jqfxhCaluuTitle : UIImageView = {
        let jqfxhCaluuTitle = UIImageView(image: UIImage(named: "jqfxh_cal_title"))
        return jqfxhCaluuTitle
    }()
    
    lazy var jqfxhCalvvYellowBg : UIImageView = {
        let jqfxhCalvvYellowBg = UIImageView(image: UIImage(named: "jqfxh_cal_yellowbg"))
        return jqfxhCalvvYellowBg
    }()
    
    lazy var jqfxhCalwwSubtitle : UILabel = {
        let jqfxhCalwwSubtitle = UILabel()
        jqfxhCalwwSubtitle.font = UIFont.jqfxhRegular12
        jqfxhCalwwSubtitle.textColor = UIColor(hex: "#EC3547")
        jqfxhCalwwSubtitle.text = "用透明化赢得信任，让借贷更安心"
        jqfxhCalwwSubtitle.textAlignment = .center
        return jqfxhCalwwSubtitle
    }()
    
    lazy var jqfxhCountxxTitle : UILabel = {
        let jqfxhCountxxTitle = UILabel()
        jqfxhCountxxTitle.font = UIFont.jqfxhRegular16
        jqfxhCountxxTitle.textColor = UIColor.black
        jqfxhCountxxTitle.text = "贷款金额"
        return jqfxhCountxxTitle
    }()
    
    lazy var jqfxhMoneyyyTf : UITextField = {
        let jqfxhMoneyyyTf = UITextField()
        jqfxhMoneyyyTf.backgroundColor = UIColor(hex: "#F8F8FA")
        jqfxhMoneyyyTf.font = UIFont.jqfxhRegular14
        jqfxhMoneyyyTf.keyboardType = .numberPad
        jqfxhMoneyyyTf.placeholder = "请输入贷款金额"
        jqfxhMoneyyyTf.textColor = UIColor.black
        jqfxhMoneyyyTf.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 16, height: 20))
        jqfxhMoneyyyTf.leftViewMode = .always
        jqfxhMoneyyyTf.jqfxhAddDoneButtoneeOnKeyboard(target: self, action: #selector(jqfxhDoneTapped))
        return jqfxhMoneyyyTf
    }()
    
    @objc func jqfxhDoneTapped() {
        self.view.endEditing(true) // 收起键盘
    }
    
    
    lazy var jqfxhRateTitlezzLabel : UILabel = {
        let jqfxhRateTitlezzLabel = UILabel()
        jqfxhRateTitlezzLabel.font = UIFont.jqfxhRegular16
        jqfxhRateTitlezzLabel.textColor = UIColor.black
        jqfxhRateTitlezzLabel.text = "年利率"
        return jqfxhRateTitlezzLabel
    }()
    
    
    
    lazy var jqfxhrateaaTf : UITextField = {
        let jqfxhrateaaTf = UITextField()
        jqfxhrateaaTf.backgroundColor = UIColor(hex: "#F8F8FA")
        jqfxhrateaaTf.font = UIFont.jqfxhRegular14
        jqfxhrateaaTf.keyboardType = .numberPad
        jqfxhrateaaTf.placeholder = "请输入年化利率"
        jqfxhrateaaTf.textColor = UIColor.black
        jqfxhrateaaTf.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 16, height: 20))
        jqfxhrateaaTf.leftViewMode = .always
        jqfxhrateaaTf.jqfxhAddDoneButtoneeOnKeyboard(target: self, action: #selector(jqfxhDoneTapped))
        return jqfxhrateaaTf
    }()

    
    
    lazy var jqfxhQixianTitlebbLabel : UILabel = {
        let jqfxhQixianTitlebbLabel = UILabel()
        jqfxhQixianTitlebbLabel.font = UIFont.jqfxhRegular16
        jqfxhQixianTitlebbLabel.textColor = UIColor.black
        jqfxhQixianTitlebbLabel.text = "借款期限"
        return jqfxhQixianTitlebbLabel
    }()
    

    lazy var jqfxhHkfsTitlebbLabel : UILabel = {
        let jqfxhHkfsTitlebbLabel = UILabel()
        jqfxhHkfsTitlebbLabel.font = UIFont.jqfxhRegular16
        jqfxhHkfsTitlebbLabel.textColor = UIColor.black
        jqfxhHkfsTitlebbLabel.text = "还款方式"
        return jqfxhHkfsTitlebbLabel
    }()
    
    
    lazy var shenqingBtn : UIButton = {
        let shenqingBtn = UIButton(type: .custom)
        shenqingBtn.setTitle("开始计算", for: .normal)
        shenqingBtn.setTitleColor(UIColor.white, for: .normal)
        shenqingBtn.backgroundColor = UIColor(hex: "#FE1C68")
        shenqingBtn.titleLabel?.font = UIFont.jqfxhRegular16
        shenqingBtn.addTarget(self, action: #selector(shenqingBtnClick), for: .touchUpInside)
        shenqingBtn.layer.cornerRadius = 8
        shenqingBtn.layer.masksToBounds = true
        return shenqingBtn
        
    }()
    
    @objc func shenqingBtnClick() {
        if let money = self.jqfxhMoneyyyTf.text {
            if money.isEmpty {
                JQFXHHUD.jqfxhShowxxText("请输入借款金额")
                return
            }else if Int(money) ?? 0 < 100{
                JQFXHHUD.jqfxhShowxxText("借款金额不能少于100")
                return
            }
        }else {
            JQFXHHUD.jqfxhShowxxText("请输入借款金额")
            return
        }
        
        if selectedMonth == 0 {
            JQFXHHUD.jqfxhShowxxText("请选择借款期限")
            return
        }
        
        if selectedType > 3 {
            JQFXHHUD.jqfxhShowxxText("请选择还款方式")
            return
        }
        
        
        if let rate = self.jqfxhrateaaTf.text {
            if rate.isEmpty {
                JQFXHHUD.jqfxhShowxxText("请输入年化利率")
                return
            }
        }else {
            JQFXHHUD.jqfxhShowxxText("请输入年化利率")
            return
        }
        
        let total = Double(self.jqfxhMoneyyyTf.text ?? "") ?? 0.0
        let month = self.selectedMonth
        let backType = self.selectedType
        let rate = Double(self.jqfxhrateaaTf.text ?? "") ?? 0.0
        if JQFXHNetworkManager.shared.isLogin {
            let loan = JQFXHLoaneeData(amount: total, term: month, repaymentType: backType, interestRate: rate)
            JQFXHLoanddStorage.shared.save(loan)
        }
        let calResult = JQFXHCalculationSuccessViewController(total: total, month: self.selectedMonth, backType: backType, rate: rate)
        self.navigationController?.pushViewController(calResult, animated: true)

    }
    
    lazy var jqfxhBackyyBtn: UIButton = {
        let jqfxhBackyyBtn = UIButton(type: .custom)
        jqfxhBackyyBtn.setBackgroundImage(UIImage(named: "jqfxh_nav_white_back"), for: .normal)
        jqfxhBackyyBtn.addTarget(self, action: #selector(jqfxhBackyyBtnClick), for: .touchUpInside)
        return jqfxhBackyyBtn
    }()
    
    
    lazy var jqfxhCalNavTitlebbLabel : UILabel = {
        let jqfxhCalNavTitlebbLabel = UILabel()
        jqfxhCalNavTitlebbLabel.font = UIFont.jqfxhRegular18
        jqfxhCalNavTitlebbLabel.textColor = UIColor.white
        jqfxhCalNavTitlebbLabel.text = "息费计算"
        return jqfxhCalNavTitlebbLabel
    }()
    
    
    @objc func jqfxhBackyyBtnClick() {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    
    func jqfxhCalculationUI() {
        self.view.backgroundColor = UIColor.jqfxhBigViewBgccGray
        self.view.addSubview(jqfxhScrollggview)
        
        jqfxhScrollggview.addSubview(jqfxhTopBgxxImg)
        jqfxhScrollggview.addSubview(jqfxhCalttPic)
        jqfxhScrollggview.addSubview(jqfxhCaluuTitle)
        jqfxhScrollggview.addSubview(jqfxhCalvvYellowBg)
        jqfxhScrollggview.addSubview(jqfxhCalwwSubtitle)
        
        jqfxhScrollggview.addSubview(jqfxhContentkkView)
        jqfxhScrollggview.snp.makeConstraints { make in
            make.edges.equalTo(self.view)
        }
        
        
        jqfxhTopBgxxImg.snp.makeConstraints { make in
            make.left.right.top.equalTo(self.view)
        }
        jqfxhContentkkView.snp.makeConstraints { make in
            make.top.equalTo(jqfxhScrollggview).offset(172+UIApplication.shared.jqfxhSafeAreaInsets.top)
            make.bottom.equalTo(jqfxhScrollggview).offset(-50)
            make.left.equalTo(self.view).offset(16)
            make.right.equalTo(self.view).offset(-16)
            make.height.equalTo(436)
        }
        jqfxhCalttPic.snp.makeConstraints { make in
            make.right.equalTo(self.view).offset(-25)
            make.bottom.equalTo(jqfxhContentkkView.snp.top)
            make.width.equalTo(126)
            make.height.equalTo(146)
        }
        
        jqfxhCaluuTitle.snp.makeConstraints { make in
            make.left.equalTo(self.view).offset(20)
            make.centerY.equalTo(jqfxhCalttPic).offset(-10)
        }
        
        jqfxhCalvvYellowBg.snp.makeConstraints { make in
            make.left.equalTo(self.view).offset(15)
            make.top.equalTo(jqfxhCaluuTitle.snp.bottom).offset(10)
        }
        jqfxhCalwwSubtitle.snp.makeConstraints { make in
            make.edges.equalTo(jqfxhCalvvYellowBg)
        }
        
        jqfxhContentkkView.addSubview(jqfxhCountxxTitle)
        jqfxhCountxxTitle.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentkkView).offset(13)
            make.top.equalTo(jqfxhContentkkView).offset(20)
        }
        jqfxhContentkkView.addSubview(jqfxhMoneyyyTf)
        jqfxhMoneyyyTf.snp.makeConstraints { make in
            make.left.equalTo(jqfxhCountxxTitle)
            make.centerX.equalTo(jqfxhContentkkView)
            make.top.equalTo(jqfxhCountxxTitle.snp.bottom).offset(5)
            make.height.equalTo(44)
        }
        
        jqfxhContentkkView.addSubview(jqfxhRateTitlezzLabel)
        jqfxhRateTitlezzLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhCountxxTitle)
            make.top.equalTo(jqfxhMoneyyyTf.snp.bottom).offset(12)
        }
        
        jqfxhContentkkView.addSubview(jqfxhrateaaTf)
        jqfxhrateaaTf.snp.makeConstraints { make in
            make.left.equalTo(jqfxhCountxxTitle)
            make.centerX.equalTo(jqfxhContentkkView)
            make.top.equalTo(jqfxhRateTitlezzLabel.snp.bottom).offset(5)
            make.height.equalTo(44)
        }
        
        jqfxhContentkkView.addSubview(jqfxhQixianTitlebbLabel)
        jqfxhQixianTitlebbLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhCountxxTitle)
            make.top.equalTo(jqfxhrateaaTf.snp.bottom).offset(12)
        }
        
        let btnWidth = (jqfxhScreenWidth - 50 - 16)/3
        for index in 0..<monthsArr.count {
            let month = monthsArr[index]
            let button = UIButton(type: .custom)
            button.setTitle(String(month) + "个月", for: .normal)
            button.setTitleColor(UIColor(hex: "#A6A6A6"), for: .normal)
            button.setTitleColor(UIColor(hex: "#FE1C68"), for: .selected)
            button.backgroundColor = UIColor(hex: "#F8F8FA")
            button.layer.cornerRadius = 4
            button.layer.masksToBounds = true
            button.frame = CGRect(x: 9 + index * (Int(btnWidth) + 8), y: 218, width: Int(btnWidth), height: 44)
            button.addTarget(self, action: #selector(monthBtnClick(sender:)), for: .touchUpInside)
            button.tag = index
            buttonArr.append(button)
            jqfxhContentkkView.addSubview(button)
        }
        
        jqfxhContentkkView.addSubview(jqfxhHkfsTitlebbLabel)
        jqfxhHkfsTitlebbLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhCountxxTitle)
            make.top.equalTo(jqfxhQixianTitlebbLabel.snp.bottom).offset(73)
        }
        
        for index in 0..<typeArr.count {
            let month = typeArr[index]
            let button = UIButton(type: .custom)
            button.setTitle(String(month), for: .normal)
            button.setTitleColor(UIColor(hex: "#A6A6A6"), for: .normal)
            button.setTitleColor(UIColor(hex: "#FE1C68"), for: .selected)
            button.backgroundColor = UIColor(hex: "#F8F8FA")
            button.layer.cornerRadius = 4
            button.layer.masksToBounds = true
            button.frame = CGRect(x: 9 + index * (Int(btnWidth) + 8), y: 302, width: Int(btnWidth), height: 44)
            button.addTarget(self, action: #selector(typeBtnClick(sender:)), for: .touchUpInside)
            button.tag = index + 100
            typebButtonArr.append(button)
            jqfxhContentkkView.addSubview(button)
        }
        
        
        jqfxhContentkkView.addSubview(shenqingBtn)
        shenqingBtn.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentkkView).offset(18)
            make.centerX.equalTo(jqfxhContentkkView)
            make.bottom.equalTo(jqfxhContentkkView).offset(-15)
            make.height.equalTo(40)
        }
        
        self.view.addSubview(jqfxhBackyyBtn)
        jqfxhBackyyBtn.snp.makeConstraints { make in
            make.left.equalTo(self.view).offset(20)
            make.top.equalTo(self.view).offset(UIApplication.shared.jqfxhSafeAreaInsets.top + 20)
            make.width.height.equalTo(30)
        }
        
        self.view.addSubview(jqfxhCalNavTitlebbLabel)
        jqfxhCalNavTitlebbLabel.snp.makeConstraints { make in
            make.centerY.equalTo(jqfxhBackyyBtn)
            make.centerX.equalTo(self.view)
        }
       
    }
    
    
    
    @objc func monthBtnClick(sender: UIButton) {
        let month = self.monthsArr[sender.tag]
        self.selectedMonth = month
        let tag = sender.tag
        for button in buttonArr {
            if button.tag == tag {
                button.isSelected = true
                button.backgroundColor = UIColor(hex: "#FFF0F5")
            }else {
                button.backgroundColor = UIColor(hex: "#F8F8FA")
                button.isSelected = false
            }
        }
    }
    
    @objc func typeBtnClick(sender: UIButton) {
        let tag = sender.tag - 100
        self.selectedType = tag
        for button in typebButtonArr {
            if button.tag == sender.tag {
                button.isSelected = true
                button.backgroundColor = UIColor(hex: "#FFF0F5")
            }else {
                button.backgroundColor = UIColor(hex: "#F8F8FA")
                button.isSelected = false
            }
        }
    }
    
}



struct JQFXHLoaneeData {
    var amount: Double
    var term: Int
    var repaymentType: Int
    var interestRate: Double
}

class JQFXHLoanddStorage {
    static let shared = JQFXHLoanddStorage()
    private let key = "loan_data_key"
    
    func save(_ data: JQFXHLoaneeData) {
        let dict: [String: Any] = [
            "amount": data.amount,
            "term": data.term,
            "repaymentType": data.repaymentType,
            "interestRate": data.interestRate
        ]
        UserDefaults.standard.set(dict, forKey: key)
    }
    
    func load() -> JQFXHLoaneeData? {
        guard let dict = UserDefaults.standard.dictionary(forKey: key) else {
            return nil
        }
        guard let amount = dict["amount"] as? Double,
              let term = dict["term"] as? Int,
              let repaymentType = dict["repaymentType"] as? Int,
              let interestRate = dict["interestRate"] as? Double else {
            return nil
        }
        return JQFXHLoaneeData(amount: amount, term: term, repaymentType: repaymentType, interestRate: interestRate)
    }
}

